import cv2
from PIL import ImageGrab, Image
import numpy
from matplotlib import pyplot as plt
import time

# 将来简化一点代码
def sleep(s):
    # 唯一一个地方的例外
    time.sleep(s)
    return

sleep(5)
#img = cv2.imread('./pycharmEditor_FullBackGround.jpg', 0)
img = numpy.asarray(ImageGrab.grab().convert('L'))
img2 = img.copy()
template = cv2.imread('../../resource/searchPicInPic/GridTop3.jpg', 0)
w, h = template.shape[::-1]
# All the 6 methods for comparison in a list
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
           'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for meth in methods:
    img = img2.copy()
    # eval 语句用来计算存储在字符串中的有效 Python 表达式
    method = eval(meth)
    # 模板匹配
    res = cv2.matchTemplate(img, template, method)
    # 设定阈值
    threshold = 0.99
    # res大于70%
    loc = numpy.where(res >= threshold)
    # 寻找最值
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    # 使用不同的比较方法，对结果的解释不同

    print("min_val:" + str(min_val))
    print("max_val:" + str(max_val))
    if max_val > threshold:
        if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
            top_left = min_loc
        else:
            top_left = max_loc
        bottom_right = (top_left[0] + w, top_left[1] + h)
        cv2.rectangle(img, top_left, bottom_right, 255, 2)
        plt.subplot(121), plt.imshow(res, cmap='gray')
        plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
        plt.subplot(122), plt.imshow(img, cmap='gray')
        plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
        plt.suptitle(meth)
        plt.show()
